<style>
</style>

<div class="col-12 col-sm-12">
    <div class="card card-tabs">
        <div class="card-header">
            <ul class="nav nav-tabs" id="custom-tabs-three-tab" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" data-toggle="pill" href="#databasebackup" data-type="template">{:lang("Database Backup")}</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#backuprestore" data-type="addon">{:lang("Backup Restore")}</a>
                </li>
            </ul>
        </div>
        <div class="card-body config-row">
            <div class="tab-content" id="custom-tabs-three-tabContent">
                <div class="tab-pane fade active show" id="databasebackup" role="tabpanel">
                    <div id="toolbar" class="toolbar">
                        {:build_toolbar('refresh')}
                        <button type="button" class="btn btn-disabled btn-success disabled all-export" data-url="export">{:lang('Database export')}</button>
                        <button type="button" class="btn btn-disabled btn-success disabled all-optimization" data-url="optimization">{:lang('Optimize table')}</button>
                        <button type="button" class="btn btn-disabled btn-success disabled all-repair" data-url="repair">{:lang('Repair table')}</button>
                    </div>
                    <table id="table"></table>
                </div>
                <div class="tab-pane fade" id="backuprestore" role="tabpanel">
                    <div id="toolbarrestore" class="toolbar">

                    </div>
                    <table id="tablerestore"></table>
                </div>
            </div>
        </div>
    </div>
</div>

{block:script}
<script>
    require(['admin','table'], function (admin, cmsTable) {
        $(function () {
            cmsTable.init({
                url: "{:url('/database/index',['type'=>'backup'])}",
                showToggle: false,
                search: false,
                pagination: false,
                escape: false,
                sortName:false,
                toolbar:'#toolbar',
                //contentLangSw: true,
                columns: [{
                    field: 'state',
                    checkbox: true,
                },{
                    field: 'name',
                    title: '{:lang("Table Name")}',
                    align: 'left',
                },{
                    field: 'rows',
                    title: '{:lang("Data volume")}',
                    align: 'left',
                },{
                    field: 'data_length',
                    title: '{:lang("Data length")}',
                    align: 'left',
                    formatter: function (value, row, index) {
                        return format_bytes(row['data_length'])
                    }
                },{
                    field: 'create_time',
                    title: '{:lang("Create time")}',
                    align: 'left',
                },{
                    field: 'name',
                    title: '{:lang("Backup state")}',
                    align: 'left',
                    formatter: function (value, row, index) {
                        return "<span class='status-"+value+"'>未备份</span>"
                    }
                },{
                    field: 'operate',
                    title: '{:lang("Operate")}',
                    align: 'left',
                    delTips: '{:lang("Are you sure to move to the recycle bin? Will include sub-sections and document data.")}',
                    formatter: function (value, row, index) {
                        let html = '';
                        html += '<a href="optimization/tables/'+row.name+'" class="btn btn-primary btn-xs text-white">{:lang("Optimize table")}</a>&nbsp';
                        html += '<a href="repair/tables/'+row.name+'" class="btn btn-primary btn-xs text-white">{:lang("Repair table")}</a>&nbsp';
                        return html
                    },
                    events: cmsTable.events.operate
                }]
            });
            $('#tablerestore').bootstrapTable({
                url: "{:url('/database/index',['type'=>'restore'])}",
                showToggle: false,
                search: false,
                pagination: false,
                escape: false,
                sortName:false,
                toolbar:'#toolbarrestore',
                //contentLangSw: true,
                columns: [{
                    field: 'name',
                    title: '{:lang("Backup Name")}',
                    align: 'left'
                },{
                    field: 'part',
                    title: '{:lang("Roll")}',
                    align: 'left',
                },{
                    field: 'size',
                    title: '{:lang("Data length")}',
                    align: 'left',
                    formatter: function (value, row, index) {
                        return format_bytes(row['size']);
                    }
                },{
                    field: 'compress',
                    title: '{:lang("Compress")}',
                    align: 'left'
                },{
                    field: 'create_time',
                    title: '{:lang("Create time")}',
                    align: 'left'
                },{
                    field: 'name',
                    title: '{:lang("Backup state")}',
                    align: 'left',
                    formatter: function (value, row, index) {
                        return "-";
                    }
                },{
                    field: 'operate',
                    title: '{:lang("Operate")}',
                    align: 'left',
                    delTips: '{:lang("Are you sure to move to the recycle bin? Will include sub-sections and document data.")}',
                    formatter: function (value, row, index) {
                        let html = '';
                        html += '<a href="javascript:void(0);" data-url="import" data-time="'+row.time+'" class="btn btn-primary btn-xs btn-import text-white">{:lang("Reduction")}</a>&nbsp';
                        html += '<a href="download/time/'+row.time+'" target="_blank" class="btn btn-primary btn-xs text-white">{:lang("Download")}</a>&nbsp';
                        html += '<a href="javascript:void(0);" data-urltime="'+row.time+'" class="btn btn-danger btn-xs text-white btn-delajax">{:lang("Delete")}</a>&nbsp';
                        return html
                    },
                    events: cmsTable.events.operate
                }]
            });
            function format_bytes(size, delimiter='') {
                units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
                for (i = 0; size >= 1024 && i < 5; i++){
                    size /= 1024;
                }
                return size.toFixed(2)+delimiter+units[i];
            }
            // 全部优化
            $('#toolbar').on('click','.all-optimization',function (e) {
                if ($(this).hasClass('disabled')) {
                    return false;
                }
                let arr = $('#table').bootstrapTable('getSelections');
                let found = $.map(arr, function(item) {
                    return item.name;
                });
                let url = Util.setUrlParams({ url:$(this).data('url')});
                //询问框
                layer.confirm(lang('Confirm operation?'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    Util.ajax({
                        url:url,data:{tables:found}
                    },'',function (data, all) {
                        layer.msg(all['msg'],{time:1000, icon:1},function (e) {
                            $('#table').bootstrapTable('refresh');
                        });
                    });
                });
            });
            // 全部修复
            $('#toolbar').on('click','.all-repair',function (e) {
                if ($(this).hasClass('disabled')) {
                    return false;
                }
                let arr = $('#table').bootstrapTable('getSelections');
                let found = $.map(arr, function(item) {
                    return item.name;
                });
                let url = Util.setUrlParams({ url:$(this).data('url')});
                //询问框
                layer.confirm(lang('Confirm operation?'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    Util.ajax({
                        url:url,
                        data:{tables:found}
                    },'',function (data, all) {
                        layer.msg(all['msg'],{time:1000, icon:1},function (e) {
                            $('#table').bootstrapTable('refresh');
                        });
                    });
                });
            });
            // 数据库备份
            $('#toolbar').on('click','.all-export',function (e) {
                if ($(this).hasClass('disabled')) {
                    return false;
                }
                let exportobj = $(this);
                let arr = $('#table').bootstrapTable('getSelections');
                let found = $.map(arr, function(item) {
                    return item.name;
                });
                let url = Util.setUrlParams({ url:$(this).data('url')});
                //询问框
                layer.confirm(lang('Confirm operation?'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    exportobj.addClass('disabled');
                    exportobj.html('正在备份...');
                    $.post(url,{tables:found},function (data) {
                        if (data.code) {
                            var icon = 1;
                        }else{
                            var icon = 5;
                        }
                        layer.msg(data['msg'],{time:1000, icon:icon},function (e) {
                            if(data.code){
                                tables = data.tables;
                                layer.msg('正在备份表('+tables[data.tab.id]+')...0.01%',{icon: 1,time: 1800000});
                                backup(data.tab,url);
                                window.onbeforeunload = function(){ return "正在备份数据库，请不要关闭！" }
                            } else {
                                exportobj.removeClass("disabled");
                                exportobj.html("数据库备份");
                            }
                        });
                    })
                });
            });
            function backup(tab, url, status) {
                status && showmsg(tables[tab.id], "开始备份...");
                $.get(url, tab, function (data) {
                    if (data.code) {
                        showmsg(tables[tab.id], data.msg);
                        if (!$.isPlainObject(data.tab)) {
                            $('.all-export').removeClass("disabled");
                            $('.all-export').html("备份完成，点击重新备份");
                            window.onbeforeunload = function () {
                                return null
                            }
                            layer.alert('所选的数据表都备份完成！',{icon: 1});
                            $("#tablerestore").bootstrapTable('refresh');
                            return;
                        }
                        if (data.code == 200) {
                            layer.msg('正在备份表('+tables[data.tab.id]+')...0.01%',{icon: 1,time: 1800000});
                        } else {
                            layer.msg(data.msg,{icon: 1,time: 1800000});
                        }
                        setTimeout(function(){
                            backup(data.tab, url, tab.id != data.tab.id);
                        },200);
                    } else {
                        layer.alert(data.msg);
                        $('.all-export').removeClass("disabled");
                        $('.all-export').html("数据库备份");
                    }
                }, "json");
            }
            function showmsg(name, msg) {
                $('.status-'+name).html(msg);
            }
            //数据还原
            $(document).on('click','.btn-import',function (e) {
                var self = $(this);
                let url = Util.setUrlParams({ url:self.data('url')});
                layer.confirm(lang('Confirm operation?'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    self.addClass('disabled');
                    self.html('正在还原...');
                    $.get(url,{time:self.data('time')}, function (data) {
                        if (data.code) {
                            var icon = 1;
                        }else{
                            var icon = 5;
                        }
                        layer.msg(data['msg'],{time:1000, icon:icon},function (e) {
                            if (data.code) {
                                layer.msg('正在还原数据...',{icon: 1,time: 1800000});
                                setTimeout(function(){
                                    importsql(data, url, self);
                                },200);
                            } else {
                                layer.alert(data.msg);
                                self.removeClass("disabled");
                                self.html("还原成功，点击可以再次还原！");
                                window.onbeforeunload = function () {
                                    return null;
                                }
                            }
                        })
                    }, "json");
                })
                window.onbeforeunload = function () {
                    return "正在还原数据库，请不要关闭！"
                }
                return false;
            });
            function importsql(data, url, self) {
                $.get(url, {"part": data.data.part,"start": data.data.start}, function(data){
                    if (data.data) {
                        layer.msg(data.msg,{icon: 1,time: 1800000});
                        setTimeout(function(){
                            importsql(data, url, self);
                        },200);
                    } else {
                        layer.alert(data.msg);
                        self.removeClass("disabled");
                        self.html("还原成功，点击可以再次还原！");
                        window.onbeforeunload = function () {
                            return null;
                        }
                    }
                }, "json");
            }
            //删除文件
            $(document).on('click','.btn-delajax',function(){
                var deltime = $(this).data('urltime');
                layer.confirm(lang('Confirm operation?'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    let url = Util.setUrlParams({ url:'delsql'});
                    Util.ajax({
                        type:'post',
                        url:url,
                        data:{deltime:deltime}
                    },'',function (data, all) {
                        layer.msg(all['msg'],{time:1000, icon:1},function (e) {
                            $('#tablerestore').bootstrapTable('refresh');
                        });
                    });
                });
            })
        })
    });
</script>
{/block:script}